package memory;

import java.util.*;

public class Board {
    private final int rows;
    private final int columns;
    private final int pairs;
    private final Square matrix [][];

    public Board (int rows, int columns) {
        this.matrix = new Square [rows][columns];
        this.rows  = rows;
        this.columns = columns;
        this.pairs = rows * columns / 2;
        
        ArrayList <Square> list = new ArrayList <Square>();
        int i = 0;

        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                matrix[r][c] = new Square(r,c);
                list.add(matrix[r][c]);
                i++;
            }
        }

        Collections.shuffle(list);

        int pairValues = 0;
        boolean everyOther = false;
        for ( Square s : list) {
            s.setPairValue(pairValues);            
            if (everyOther) pairValues++;
            everyOther = !everyOther;
        }

    }

    public Square getSquare (int row, int column) {
        return matrix[row][column];
    }

    public Square [][] getBoard () {
        return matrix;
    }

    public int getRows() {
        return rows;
}

    public int getColumns() {
        return columns;
    }

    public boolean allMatched () {
        for (Square []  ms  : matrix) {
            for (Square s : ms) {
                if (!s.isPaired()) {
                    return false;
                }
            }
        }
        return true;
    }
}

